/**
 * WidgetEventPhoneInput module
 */

 import eventHelper from "../../../utils/EventHelper";

 import React,{Component} from "react";
 import consts from "../../../consts/consts";
 import CommonProperty from "./CommonProperty";
 import Validator from "../../../utils/validator/Validator";
 class WidgetEventPhoneInput extends Component{
    mixins: [CommonProperty]
    constructor(props) {
        super(props);
        this.state = {             
            number: "",
            errorInfo: ""
        };
    }
    getInitialState(){
        return {
            number: "",
            errorInfo: ""
        }
    }
    componentDidMount(){
        var data = this.props.widget;
        this.number = data.action.number || "";
        if (this.number){
            this.setState({
                number: this.number
            });
        }
    }
    handleOnInputPhone(e){
        var input = $(e.target);
        this.number = input.val();
        this.setState({
            number: this.number
        });
    }
    checkValidate(){
        var validator = Validator();

        validator.addRule($(this.refs.phoneInput), [{
            validator: "empty",
            error: $._("tel number can not be empty")
        }, {
            validator: "templatePhone",
            error: $._("Please insert your phone")
        }]);

        var errors = validator.execute();
        return errors;
    }
    handleOnInputBlur(){
        let errors = this.checkValidate();
        const {widget,updateWidget,setState} = this.props;
        let data = widget;
        this.setState({
            errorInfo: errors
        });
        if (errors){
            return;
        }
        data.action.number = this.number;
        this.updateWidgetData(data);
        eventHelper.trigger(consts.EVENTS.THREED_WIDGET_PROPERTY_CHANGED, data);
    }
    updateWidgetData(data){
        const {updateWidget,setState} = this.props;
        setState({selectedWidget: data});
        updateWidget(data);
    }
    render(){
        var errorNode = "";
        if (this.state.errorInfo){
            errorNode = <div className="alerterror" style={{ padding: 0 }}>{ this.state.errorInfo }</div>
        }

        return (
            <div className="form-group rowli">
                <label className="control-label">{$._('Phone No')}</label>
                <input ref="phoneInput" onChange={ (e) => this.handleOnInputPhone(e) } onBlur={(e) =>  this.handleOnInputBlur(e) } className="rightnumber form-control" value={ this.state.number } name="number" type="text" autoFocus="true" placeholder={$._('insert your phone')} />
                {errorNode}
            </div>
        )
    }
 }

 module.exports = WidgetEventPhoneInput;
